import React, { Children } from "react";
import { Select, Button, DatePicker, Tooltip } from 'antd';
import {
  QuestionCircleFilled,
} from '@ant-design/icons';
import './style/style.less'
import '@/font/iconfont.css'
import TheTable from "@/components/TheTable";
import { apiGetEventEventPageList, } from '@/request/dataBoard'
import _ from 'lodash'
import moment from 'moment';
import TheButton from "@/components/TheButton";
import Json2Excel from '@/utils/Json2Excel'

const { RangePicker } = DatePicker;

class Index extends React.Component {
  state = {
    dataSource: [],
    dateType: "day",
    selectVal: "all",
    beginTime: moment().subtract(1, 'days').format('yyyy-MM-DD'),
    endTime: moment().subtract(1, 'days').format('yyyy-MM-DD'),
    time: '',
    defaultValueTime: '',
    nextTime: "",
    loading: false,
    columns: [
      {
        title: "序号",
        key: "index",
        dataIndex: "index",
        render: (text, render, index) => {
          return index + 1
        }
      },
      {
        title: "业务",
        dataIndex: "businessTypeName",
        key: "businessTypeName"
      },
      {
        title: "页面",
        dataIndex: "pageTypeName",
        key: "pageTypeName",
      },
      {
        title: "访客人数",
        dataIndex: "visitCount",
        key: "visitCount",
      },
      {
        title: "浏览次数",
        dataIndex: "viewCount",
        key: "viewCount",
      },
      {
        title: "平均停留时长(分钟)",
        dataIndex: "stayDuration",
        key: "stayDuration",
      },
    ],
    exportLoading: false
  }
  async componentDidMount() {
    await this.getData();
  }
  getData = async () => {
    let res = await apiGetEventEventPageList({ "dateType": this.state.dateType, "businessType": this.state.selectVal, "beginDate": this.state.beginTime, "endDate": this.state.endTime })
    if (res.data && res.code === 0) {
      res.data.eventPageList.forEach(item => {
        item.stayDuration = (Number(item.stayDuration) / 60).toFixed(1)
      })
      this.setState({
        dataSource: res.data.eventPageList,
        time: res.data.beginTime + "~" + res.data.endTime
      })
    }



  }

  handleChange = async (value) => {
    this.setState({
      selectVal: value
    }, () => {
      this.getData();
    })



  };


  onChange = (dates, dateStrings, type) => {
    console.log(dates, '===========', moment(dates).startOf('month').format('YYYY-MM-DD'));

    if (dates) {

      let beginTime = "";
      let endTime = ""
      let time = ""
      if (type == "year") {
        beginTime = moment(dates).startOf('year').format('YYYY-MM-DD')
        endTime = moment(dates).endOf('year').format('YYYY-MM-DD')
        time = beginTime + '~' + endTime
      }
      if (type == "month") {
        beginTime = moment(dates).startOf('month').format('YYYY-MM-DD')
        endTime = moment(dates).endOf('month').format('YYYY-MM-DD')
        time = beginTime + '~' + endTime
      }
      if (type == "week") {
        beginTime = moment(dates).startOf('week').format('YYYY-MM-DD')
        endTime = moment(dates).endOf('week').format('YYYY-MM-DD')
        time = beginTime + '~' + endTime
      }
      if (type == "day") {
        beginTime = dateStrings
        endTime = dateStrings
        time = beginTime
      }
      if (type == "maybe") {
        beginTime = dateStrings[0]
        endTime = dateStrings[1]
        time = beginTime + "~" + endTime
      }

      this.setState({
        beginTime: beginTime,
        endTime: endTime,
        dateType: type == "maybe" ? "day" : type,
        time: time
      }, () => {
        this.getData();
      })
    } else {
    }
  };

  open = (a) => {
    this.setState({
      defaultValueTime: null
    })
    console.log(a, 'open');
  }

  toExprot = () => {
    const { beginTime, endTime, selectVal, dataSource, } = this.state
    this.setState({
      exportLoading: true
    })
    let label = ""
    switch (selectVal) {
      case "all":
        label = "全部"
        break;
      case "onlineMall":
        label = "线上商城"
        break;
      case "pet":
        label = "宠圈"
        break;
      case "store":
        label = "门店"
        break;
      case "petSteward":
        label = "宠物管家"
        break;
      default:
        break;
    }
    dataSource.map((item, index) => {
      item.index = index + 1
    })
    const option= {
      header: [
        {
          title: '业务范围：' + label + "\r\n" + "统计时间：" + beginTime + "-" + endTime,
          prop: '',
          children: [
            { prop: 'index', title: '序号' },
            { prop: 'businessTypeName', title: '业务' },
            { prop: 'pageTypeName', title: '页面' },
            { prop: 'visitCount', title: '访客人数' },
            { prop: 'viewCount', title: '浏览次数' },
            { prop: 'stayDuration', title: '平均停留时长（分钟）' },
          ]
        }
      ],
      fileName:  "流量页面",
      dataSource,
    }
    this.setState({
      exportLoading: false
    })
    Json2Excel(option);
  }
  render() {
    const { dataSource, loading, columns, time, defaultValueTime, exportLoading } = this.state

    return <div className={"p-layout-box configuration"}>
      <p className="realTitle"> <span>统计时间：{time}</span></p>
      <div className="realTime">


        <div>
          业务范围：
          <Select
            defaultValue="all"
            style={{
              width: 200,
            }}
            onChange={this.handleChange}
            options={[
              {
                value: 'all',
                label: '全部',
              },
              {
                value: 'onlineMall',
                label: '线上商城',
              },
              {
                value: 'pet',
                label: '宠圈',
              },
              {
                value: 'store',
                label: '门店',
              },
              {
                value: 'petSteward',
                label: '工具',
              },
            ]}
          />

        </div>
        <div className="searchBtn">
          <div className="box">
            <Button type="primary">年</Button>
            <DatePicker allowClear={false} onOpenChange={this.open} picker="year" value={defaultValueTime} onChange={(a, b) => this.onChange(a, b, "year")} className="dateBtn"  ></DatePicker>
          </div>
          <div className="box">
            <Button type="primary">月</Button>
            <DatePicker allowClear={false} onOpenChange={this.open} format={'YYYY-MM'} value={defaultValueTime} picker="month" onChange={(a, b) => this.onChange(a, b, "month")} className="dateBtn"  ></DatePicker>
          </div>
          <div className="box">
            <Button type="primary" >周</Button>
            <DatePicker allowClear={false} onOpenChange={this.open} value={defaultValueTime} picker="week" onChange={(a, b) => this.onChange(a, b, "week")} className="dateBtn"  ></DatePicker>
          </div>
          <div className="box">
            <Button type="primary" >日</Button>
            <DatePicker allowClear={false} onOpenChange={this.open} format={'YYYY-MM-DD'} value={defaultValueTime} onChange={(a, b) => this.onChange(a, b, "day")} className="dateBtn"  ></DatePicker>
          </div>
          <div className="box">
            <Tooltip title="自定义支持在可选时间范围内，对任意连续自然天的数据进行分析，人群相关的指标默认将单日的数据直接相加计算。 自定义周期查询下，默认将所选时间段与上一个时间段进行对比，例如，若查询时间选择11.04-11.06（本期数），则上一个时间段为11.01-11.03（上期数），对比值=（本期数－上期数）÷ 上期数 ×100%。"> <Button type="primary">自定义<QuestionCircleFilled /></Button></Tooltip>
            <RangePicker allowClear={false} onOpenChange={this.open} format={'YYYY-MM-DD'} value={defaultValueTime} onChange={(a, b) => this.onChange(a, b, "maybe")} className="dateBtn"  ></RangePicker>
          </div>
        </div>
        <div style={{ marginLeft: '40px' }}>
          <TheButton haspermi={["dataBoard:flowPage:export"]} type="primary" size="middle" onClick={this.toExprot} loading={exportLoading}>导出</TheButton>
        </div>
      </div>
      <TheTable bordered loading={loading} dataSource={dataSource} columns={columns} />
    </div>
  }
}

export default Index;
